import React, {useEffect, useState} from 'react'
import {Button, Space, message} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history} from 'umi'
import {
	PlusOutlined,
	ArrowUpOutlined,
	ArrowDownOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import styles from '../index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import Modal from '@/components/Modal'
import {
	deleteWarehousein,
	getErrorListPage,
	getWarehouseinList,
	warehouseImportData,
} from '@/service/storage/inAtorage'
import CustomTable from '@/components/Table'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {downloadDocumentUrl} from '@/service/common/download'

interface DataType {
	inWarehouseStatus: string
	id: string
	inWarehouseNo: string
	inWarehouseStatusStr: string
	inWarehouseTypeStr: string
	sourceDocNo: string
	carNo: string
	carFrameNo: string
	carModel: string
	cityName: string
	inWarehouseName: string
	warehouseLocationCode: string
	affiliatedCompanyName: string
	createTime: string
	remark: string
}

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const vehicle = (props: any) => {
	const {dictData, warehouseData} = props
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [id, setId] = useState<string>('')
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	// 获取入库列表列表
	const getData = () => {
		setLoading(true)
		getWarehouseinList({
			...params,
			...searchData,
			goodsType: '1',
			inOutType: '1',
		})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	const deleteData = () => {
		deleteWarehousein(id)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					setIsModalOpen(false)
					getData()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '入库单号',
			dataIndex: 'inWarehouseNo',
			align: 'center',
			width: 150,
		},
		{
			title: '状态',
			dataIndex: 'inWarehouseStatusStr',
			align: 'center',
			width: 80,
		},
		{
			title: '类型',
			dataIndex: 'inWarehouseTypeStr',
			align: 'center',
			width: 140,
		},
		{
			title: '来源单号',
			dataIndex: 'sourceDocNo',
			align: 'center',
			width: 150,
		},
		{
			title: '车牌号',
			dataIndex: 'carNo',
			align: 'center',
			width: 120,
		},
		{
			title: '车架号',
			dataIndex: 'carFrameNo',
			align: 'center',
			width: 120,
		},
		{
			title: '车型',
			dataIndex: 'carModel',
			align: 'center',
			width: 160,
		},
		{
			title: '入库时间',
			dataIndex: 'inWarehouseTime',
			align: 'center',
			width: 160,
			render: (text, record) => (
				<>{record?.inWarehouseStatus === '2' ? text : '-'}</>
			),
		},
		{
			title: '所属仓库',
			dataIndex: 'inWarehouseName',
			align: 'center',
			width: 100,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 100,
		},
		{
			title: '所在库位',
			dataIndex: 'warehouseLocationCode',
			align: 'center',
			width: 100,
		},
		{
			title: '所属公司',
			dataIndex: 'affiliatedCompanyName',
			align: 'center',
			width: 150,
		},
		{
			title: '创建时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 160,
		},
		{
			title: '备注',
			dataIndex: 'remark',
			align: 'center',
			ellipsis: true,
			width: 200,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 120,
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_storage_warehousing_view">
						<Button
							type="link"
							onClick={() => {
								history.push({
									pathname: '/storage/warehousing/view',
									query: {
										id: record?.id,
										type: 'vehicle',
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					{record.inWarehouseStatus === '1' ? (
						<>
							<Permissions permissionID="amc_storage_warehousing_edit">
								<Button
									type="link"
									onClick={() => {
										history.push({
											pathname:
												'/storage/warehousing/edit',
											query: {
												id: record?.id,
												type: 'vehicle',
											},
										})
									}}>
									编辑
								</Button>
							</Permissions>
							<Permissions permissionID="amc_storage_warehousing_delete">
								<Button
									type="link"
									onClick={() => {
										setId(record?.id)
										setIsModalOpen(true)
									}}>
									删除
								</Button>{' '}
							</Permissions>
						</>
					) : (
						''
					)}
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '入库单号',
					name: 'inWarehouseNo',
					key: 'inWarehouseNo',
				},
				{
					type: 'select',
					key: 'inWarehouseStatus',
					name: 'inWarehouseStatus',
					label: '状态',
					keys: 'dictKey',
					title: 'dictValue',
					items: dictData?.IN_WAREHOUSE_STATUS,
				},
				{
					type: 'select',
					key: 'inWarehouseType',
					name: 'inWarehouseType',
					label: '入库类型',
					keys: 'dictKey',
					title: 'dictValue',
					items: dictData?.IN_WAREHOUSE_TYPE,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'time',
					subtype: 'date',
					label: '创建时间（起）',
					name: 'createStartTime',
					key: 'createStartTime',
				},
				{
					type: 'time',
					subtype: 'date',
					label: '创建时间（止）',
					name: 'createEndTime',
					key: 'createEndTime',
				},
				{},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'time',
					subtype: 'date',
					label: '入库时间（起）',
					name: 'inWarehouseStartTime',
					key: 'inWarehouseStartTime',
				},
				{
					type: 'time',
					subtype: 'date',
					label: '入库时间（止）',
					name: 'inWarehouseEndTime',
					key: 'inWarehouseEndTime',
				},
				{},
			],
		},
		{
			type: 'group',
			key: 'group4',
			groupItems: [
				{
					type: 'input',
					label: '车牌号',
					name: 'carNo',
					key: 'carNo',
				},
				{
					type: 'input',
					label: '车架号',
					name: 'carFrameNo',
					key: 'carFrameNo',
				},
				{
					type: 'input',
					label: '车型',
					name: 'carModel',
					key: 'carModel',
				},
			],
		},
		{
			type: 'group',
			key: 'group5',
			groupItems: [
				{
					type: 'select',
					key: 'warehouseArchivesId',
					name: 'warehouseArchivesId',
					label: '所属仓库',
					keys: 'id',
					title: 'warehouseName',
					items: warehouseData,
				},
				{},
				{},
			],
		},
	]
	const onFinish = (values: any) => {
		const momentTime = (time: string, type: string) => {
			if (time) {
				if (type === 'state') {
					return moment(time).format('YYYY-MM-DD 00:00:00')
				}
				return moment(time).format('YYYY-MM-DD 23:59:59')
			}
			return null
		}
		const newSearch = {
			...values,
			createStartTime: momentTime(values?.createStartTime, 'state'),
			createEndTime: momentTime(values?.createEndTime, 'end'),
			inWarehouseStartTime: momentTime(
				values?.inWarehouseStartTime,
				'state',
			),
			inWarehouseEndTime: momentTime(values?.inWarehouseEndTime, 'end'),
		}
		setSearchData(newSearch)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '状态',
			dataIndex: 'inWarehouseStatusStr',
			align: 'center',
			width: 100,
		},
		{
			title: '入库类型',
			dataIndex: 'inWarehouseTypeStr',
			align: 'center',
			width: 150,
		},
		{
			title: '入库仓',
			dataIndex: 'inWarehouseName',
			align: 'center',
			width: 120,
		},
		{
			title: '失败原因',
			dataIndex: 'reason',
			align: 'center',
			fixed: 'right',
			width: 200,
		},
	]

	return (
		<div className={styles.warehousing}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_storage_warehousing_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push({
										pathname: '/storage/warehousing/add',
										query: {
											type: 'vehicle',
										},
									})
								}}>
								新增数据
							</Button>
						</Permissions>
						<Permissions permissionID="amc_storage_warehousing_add">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => setIsUploadModalOpen(true)}>
								导入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_storage_warehousing_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '132',
										queryDesc:
											'入库管理车辆导出,resourceId:132',
										queryParam: {
											...searchData,
											goodsType: '1',
											inOutType: '1',
										},
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<Modal
				text="确认要删除该数据吗？"
				onSubmit={deleteData}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={warehouseImportData}
				onTableList={getErrorListPage}
				getListData={getData}
				type="1"
				goodsType="1"
				downloadUrl="storage/车辆入库.xlsx"
				uploadFileUrl={`${modalApi.storage}/import/warehouse/check`}
				columns={errorColumns}
				sourceId={24}
				templateType="车辆入库"
			/>
		</div>
	)
}

export default vehicle
